﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.OAuthLogin.Config;
using Microsoft.AspNetCore.OAuthLogin.Model;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;

namespace Microsoft.AspNetCore.OAuthLogin
{
    /// <summary>
    /// 微信登陆
    /// </summary>
    public class Wechat : BaseLogin
    {
        private OAuthCredentials _credentials;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="httpContextAccessor"></param>
        /// <param name="options"></param>
        public Wechat(IHttpContextAccessor httpContextAccessor, IOptions<OAuthCredentials> options)
            : base(httpContextAccessor)
        {
            this._credentials = options.Value;
        }

        private string authorize_url { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public override string Authorize_Url => authorize_url;

        /// <summary>
        /// 登陆验证
        /// </summary>
        /// <returns></returns>
        public OAuthResult Authorize()
        {
            OAuthResult result = new OAuthResult();
            authorize_url = $"https://open.weixin.qq.com/connect/qrconnect?appid={_credentials.Wechat.client_id}&redirect_uri={CallbackUrl}&response_type=code&scope=snsapi_login#wechat_redirect";

            if (String.IsNullOrEmpty(AuthorizeCode))
            {  
                return null;
            }
            result.Token = Accesstoken(AuthorizeCode);
            if (result.Token != null && result.Token.Value<int>("errcode ") == 0)
            {
                result.User = UserInfo(result.Token.Value<string>("access_token"), result.Token.Value<string>("openid"));
                if (result.User.Value<int>("errcode ") == 0)
                {
                    result.code = 0;
                    result.User = result.User;
                }
                else
                {
                    result.errormsg = result.User.Value<string>("errmsg");
                    result.code = 2;
                }
            }
            else
            {
                result.errormsg = result.Token.Value<string>("errmsg");
                result.code = 1;
            }
            return result;
        }

        /// <summary>
        /// 获取token
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        private JObject Accesstoken(string code)
        {
            string oauth_url = $"https://api.weixin.qq.com/sns/oauth2/access_token";
            var data = new SortedDictionary<string, string>();
            data.Add("appid", _credentials.Wechat.client_id);
            data.Add("secret", _credentials.Wechat.client_secret);
            data.Add("grant_type", "authorization_code");
            data.Add("code", code);

            var Params = String.Join("&", data.Select(x => x.Key + "=" + x.Value).ToArray());
            using (var httpClient = new HttpClient())
            {
                var response = httpClient.PostAsync(oauth_url, new StringContent(Params)).Result;
                return JsonConvert.DeserializeObject<JObject>(response.Content.ReadAsStringAsync().Result);
            }
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="token"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        private JObject UserInfo(string token, string uid)
        {
            string user_info_url = $"https://api.weixin.qq.com/sns/userinfo?access_token={token}&openid={uid}";
            using (var wc = new HttpClient())
            {
                var response = wc.GetAsync(user_info_url).Result;

                var result = response.Content.ReadAsStringAsync().Result;
                var user = JsonConvert.DeserializeObject<JObject>(result);
                return user;
            }
        }




    }
}
